package com.my.assembly.handler;

import android.app.Activity;
import android.media.MediaRecorder;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.my.assembly.bridge.BridgeHandler;
import com.my.assembly.bridge.BridgeWebView;
import com.my.assembly.bridge.CallBackFunction;
import com.my.assembly.config.Config;
import com.my.assembly.utils.HandlerUtils;

import org.xutils.common.util.KeyValue;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * <pre>
 *     author : wxq
 *     time   : 2019/01/09
 *     desc   :
 *     version: 1.0
 * </pre>
 */
public class RecordHandler implements BridgeHandler {

    private Activity mContext;
    private BridgeWebView mWebView;

    private MediaRecorder mMediaRecorder;

    private boolean isRecording = false;
    private File mCurrentRecordFile;


    public RecordHandler(Activity context, BridgeWebView webView) {
        this.mContext = context;
        this.mWebView = webView;
    }

    @Override
    public void handler(String data, CallBackFunction function) {
        JsonObject jsonObject = (JsonObject) new JsonParser().parse(data);
        String type = jsonObject.get("type").getAsString();
        if ("start".equals(type)) {
            //开始录音
            startRecorder();
        } else {
            //结束录音
            //上传录音文件
            stopRecorder();
            upRecordFile();
        }
    }

    private void startRecorder() {
        if (isRecording) return;
        try {
            mCurrentRecordFile = new File(Environment.getExternalStorageDirectory(), "/record/record" + System.currentTimeMillis() + ".amr");
            mCurrentRecordFile.mkdirs();
            if (mCurrentRecordFile.exists()) {
                mCurrentRecordFile.delete();
            }
            mMediaRecorder = new MediaRecorder();
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
            mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            mMediaRecorder.setOutputFile(mCurrentRecordFile.getAbsolutePath());
            mMediaRecorder.setOnErrorListener(new MediaRecorder.OnErrorListener() {
                @Override
                public void onError(MediaRecorder mr, int what, int extra) {
                    mMediaRecorder.stop();
                    mMediaRecorder.release();
                    isRecording = false;
                    Toast.makeText(mContext, "录音发生错误", Toast.LENGTH_SHORT).show();
                }
            });
            mMediaRecorder.prepare();
            mMediaRecorder.start();
            isRecording = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void stopRecorder() {
        isRecording = false;
        if (mMediaRecorder != null) {
            mMediaRecorder.stop();
            mMediaRecorder.release();
        }
        mMediaRecorder = null;
    }

    private void upRecordFile() {
        if (mCurrentRecordFile == null || !mCurrentRecordFile.exists()) {
            return;
        }
        RequestParams params = new RequestParams(Config.base_url + "/WebApp/AppPhotoBooks/AppUploadVoice");
        params.setAsJsonContent(true);
        List<KeyValue> list = new ArrayList<>();
        list.add(new KeyValue("file", mCurrentRecordFile));
//        String ctime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date(file.lastModified()));
        org.xutils.http.body.MultipartBody body = new org.xutils.http.body.MultipartBody(list, "UTF-8");
        params.setRequestBody(body);
        params.addHeader("DEVICEINFO", "JxRaZezavm3HXM3d9pWnYiqqQC1SJbsU");
//        params.addBodyParameter("timestamp", ctime);
        x.http().post(params, new org.xutils.common.Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(final String result) {
                HandlerUtils.post(new Runnable() {
                    @Override
                    public void run() {
                        mWebView.callHandler("pronunciation", result, new CallBackFunction() {
                            @Override
                            public void onCallBack(String data) {

                            }
                        });
                    }
                });
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.i("wxq", "上传录音文件失败" + ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
}
